package net.gazhi.delonix.rbac.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import net.gazhi.delonix.core.annonation.ApiAction;
import net.gazhi.delonix.core.annonation.ApiController;
import net.gazhi.delonix.core.annonation.ApiLevel;
import net.gazhi.delonix.core.web.AbstractAnnotationController;
import net.gazhi.delonix.rbac.entity.LoginUser;
import net.gazhi.delonix.rbac.entity.Ticket;
import net.gazhi.delonix.rbac.form.LoginForm;
import net.gazhi.delonix.rbac.service.TicketService;

/**
 * 首页控制器<br>
 * 默认调用 indexHandler 的 index 方法，具体参见：IndexHandler
 * 
 * @author jeffreylin@gazhi.net
 *
 */
@Controller
@ApiController("登录与首页")
public class IndexController extends AbstractAnnotationController {

	@Autowired
	private IndexHandler indexHandler;

	@Autowired
	private TicketService ticketService;

	@RequestMapping("/")
	@ApiAction(name = "首页", level = ApiLevel.USER_DEFAULT)
	public ModelAndView index() {
		return this.indexHandler.index();
	}

	@RequestMapping("/login")
	@ApiAction(name = "登录", level = ApiLevel.PUBLIC)
	public ModelAndView login(HttpServletRequest request, @RequestBody(required = false) @Valid LoginForm form, BindingResult result) {
		if (request.getMethod().equalsIgnoreCase("GET")) {
			return new ModelAndView();
		}
		Ticket ticket = this.ticketService.generateTicket(form, result);
		return new ModelAndView("login-result").addObject("result", result).addObject("ticket", ticket);
	}

	@RequestMapping("/logout")
	@ApiAction(name = "退出", level = ApiLevel.PUBLIC)
	public ModelAndView logout(HttpServletRequest request) {
		LoginUser loginUser = (LoginUser) request.getAttribute(LoginUser.LOGIN_USER_ATTRIBUTE);
		request.removeAttribute(LoginUser.LOGIN_USER_ATTRIBUTE);
		this.ticketService.logout(loginUser);
		return super.msgView("退出成功！");
	}

}
